package com.smit.icastplus.ssdp;

import com.smit.utils.LogUtil;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * 组播socket
 */
class SSDPMultiCastSocket {
    private static final String TAG = SSDPMultiCastSocket.class.getSimpleName();
    private MulticastSocket mSSDPSocket;
    private InetAddress multiCastAddress;

    /**
     * 构造方法
     *
     * @throws IOException 绑定端口失败
     */
    public SSDPMultiCastSocket() throws IOException {
        mSSDPSocket = new MulticastSocket();
        initSocket();
    }

    private void initSocket() throws IOException {
        mSSDPSocket.setLoopbackMode(true);
        mSSDPSocket.setTimeToLive(1);
        multiCastAddress = InetAddress.getByName(SSDPConstants.SSDP_ADDRESS);
        mSSDPSocket.joinGroup(multiCastAddress);
    }

    /**
     * 用来发多播消息
     *
     * @param data 多播内容
     * @throws IOException 发送失败
     */
    public void sendMessage(String data) throws IOException {
        DatagramPacket dp = new DatagramPacket(data.getBytes("UTF-8"), data.length(), multiCastAddress,
                SSDPConstants.SSDP_PORT);

        mSSDPSocket.send(dp);
    }

    /**
     * 关闭socket
     */
    public void close() {
        if (mSSDPSocket != null) {
            LogUtil.debug(TAG, "close SSDP socket~~~");
            try {
                mSSDPSocket.leaveGroup(multiCastAddress);
            } catch (IOException e) {
                LogUtil.debug(TAG, "leaveGroup-error:" + e.getMessage());
            }
            mSSDPSocket.close();
            mSSDPSocket = null;
            multiCastAddress = null;
        }
    }
}
